package com.ds.yuntukubackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ds.yuntukubackend.annotation.AuthCheck;
import com.ds.yuntukubackend.contant.UserConstant;
import com.ds.yuntukubackend.exception.ErrorCode;
import com.ds.yuntukubackend.exception.ThrowUtils;
import com.ds.yuntukubackend.model.dto.user.UserCreateRequest;
import com.ds.yuntukubackend.model.dto.user.UserQueryRequest;
import com.ds.yuntukubackend.model.dto.user.UserUpdateRequest;
import com.ds.yuntukubackend.model.entity.User;
import com.ds.yuntukubackend.model.enums.UserRoleEnum;
import com.ds.yuntukubackend.model.vo.LoginUserVO;
import com.ds.yuntukubackend.model.vo.UserVO;
import com.ds.yuntukubackend.service.UserService;
import com.ds.yuntukubackend.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lenovo
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-01-26 21:34:23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 用户注册
     * @param account 账号
     * @param password 密码
     * @param checkPassword 确认密码
     * @return 用户的id
     */
    @Override
    @Transactional // 添加事务注解: 确保数据库只会添加一条记录，由于账号被添加了唯一性约束，不加也行
    //测试使用@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public long userRegister(String account, String password, String checkPassword) {
        //1.校验参数
        ThrowUtils.throwIf(StrUtil.hasBlank(account, password, checkPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(StrUtil.length(account) < 4 || StrUtil.length(account) > 12, ErrorCode.PARAMS_ERROR, "账号应在4-12位之间");
        ThrowUtils.throwIf(StrUtil.length(password) < 4 || StrUtil.length(password) > 16, ErrorCode.PARAMS_ERROR, "密码应在4-16位之间");
        ThrowUtils.throwIf(StrUtil.length(checkPassword) < 4 || StrUtil.length(checkPassword) > 16, ErrorCode.PARAMS_ERROR, "密码应在4-16位之间");
        ThrowUtils.throwIf(!password.equals(checkPassword), ErrorCode.PARAMS_ERROR, "两次密码不一致");

        //2.检查开户账号是否和数据库已有的重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        boolean exists = this.baseMapper.exists(queryWrapper);
        ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "账号已存在");
        //3.密码加密
        String encryptPassword = getEncryptPassword(password);
        //4.插入数据到数据库
        User user = new User();
        user.setAccount(account);
        user.setPassword(encryptPassword);
        user.setNickname("无名");
        user.setRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        return user.getId();
    }




    /**
     * 用户登录
     *
     * @param account  账号
     * @param password 密码
     * @param request  请求
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO userLogin(String account, String password, HttpServletRequest request) {
        //1.校验参数
        ThrowUtils.throwIf(StrUtil.hasBlank(account, password), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(StrUtil.length(account) < 4 || StrUtil.length(account) > 12, ErrorCode.PARAMS_ERROR, "账号应在4-12位之间");
        ThrowUtils.throwIf(StrUtil.length(password) < 4 || StrUtil.length(password) > 16, ErrorCode.PARAMS_ERROR, "密码应在4-16位之间");
        //2.对密码进行加密
        String encryptPassword = getEncryptPassword(password);
        //3.查询数据库用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account)
                    .eq("password", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR,"账号或密码错误");
        //4.保存用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取登录用户信息（内部使用）
     * @param request  请求
     * @return  登录用户信息 User
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        //1.判断用户是否登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(currentUser == null || currentUser.getId() == null, ErrorCode.NOT_LOGIN_ERROR);
        //2. 查询数据库用户信息，以防止缓存信息未修改
        currentUser = this.getById(currentUser.getId());
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR,"用户已被删除");

        return currentUser;
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @Override
    public Boolean userLogout(HttpServletRequest request) {
        //1.判断用户是否登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(userObj == null, ErrorCode.OPERATION_ERROR,"未登录");
        //2.移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }


    /**
     * 获取加密后的密码
     * @param userPassword 明文密码
     * @return 加密密码
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        //加盐，混淆密码
        final String PRI_SALT = "ds";
        final String POST_SALT = "yuntuku";
        //MD5单向哈希函数,不防碰撞
        return DigestUtils.md5DigestAsHex((PRI_SALT + userPassword + POST_SALT).getBytes());
    }

    /**
     * 获取脱敏后的用户登录信息
     * @param user 用户
     * @return  脱敏后的用户登录信息
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if(user == null){
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user,loginUserVO);
        return loginUserVO;
    }

    /**
     * 获取脱敏后的用户信息
     *
     * @param user 用户
     * @return 脱敏后的用户信息
     */
    @Override
    public UserVO getUserVO(User user) {
        if(user == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户信息列表
     *
     * @param userList 用户列表
     * @return 脱敏后的用户信息列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if(CollectionUtil.isEmpty(userList)){
            return null;
        }
        return userList.stream().map(this::getUserVO)
                                .collect(Collectors.toList());
    }

    /**
     * 创建用户
     * @param userCreateRequest 用户信息
     * @return true/false
     */
    @Override
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Long createUser(UserCreateRequest userCreateRequest) {
        //1.参数校验
        String account = userCreateRequest.getAccount();
        ThrowUtils.throwIf(StrUtil.isBlank(account)
                                    ||StrUtil.length(account) <4
                                    ||StrUtil.length(account) >12
                ,ErrorCode.PARAMS_ERROR,"账号应在4-12位之间");
        //2.查询数据库用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        boolean exists = this.baseMapper.exists(queryWrapper);
        ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "账号已存在");
        //3.设置默认密码为：root
        final String DEFAULT_PASSWORD = "root";
        String encryptPassword = getEncryptPassword(DEFAULT_PASSWORD);
        //4. 保存用户信息
        User user = new User();
        BeanUtil.copyProperties(userCreateRequest,user);
        user.setPassword(encryptPassword);
        boolean result = this.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "用户创建失败");
        return user.getId();
    }

    /**
     * 根据User的字段获取查询条件
     * @param userQueryRequest 可获取查询条件的用户字段
     * @return 查询条件queryWrapper
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        Long id = userQueryRequest.getId();
        String account = userQueryRequest.getAccount();
        String nickname = userQueryRequest.getNickname();
        String profile = userQueryRequest.getProfile();
        String role = userQueryRequest.getRole();
        //排序字段
        String sortField = userQueryRequest.getSortField();
        //排序顺序
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(id),"id",id);
        queryWrapper.eq(StrUtil.isNotEmpty(account),"account",account);
        queryWrapper.like(StrUtil.isNotEmpty(nickname),"nickname",nickname);
        queryWrapper.like(StrUtil.isNotEmpty(profile),"profile",profile);
        queryWrapper.eq(StrUtil.isNotEmpty(role),"role",role);
        //ascend 升序 ，boolean isAsc : true，则表示按升序排序（ASC）；false，则表示按降序排序（DESC）
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField),sortOrder.equals("ascend"),sortField);
        return queryWrapper;
    }

    /**
     * 更新用户信息（仅管理员可用）
     * @param userUpdateRequest
     * @return
     */
    @Override
    public Boolean updateUser(UserUpdateRequest userUpdateRequest) {
        ThrowUtils.throwIf(userUpdateRequest == null
                        || userUpdateRequest.getId() == null
                        , ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(userUpdateRequest,user);
        boolean result = updateById(user);
        ThrowUtils.throwIf(!result,ErrorCode.SYSTEM_ERROR,"用户更新失败");
        return true;
    }

    /**
     * 获取用户分页信息
     * 脱敏信息
     * 管理员可用
     * @param userQueryRequest
     * @return
     */
    @Override
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Page<UserVO> getUserVOPage(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = userQueryRequest.getCurrent();
        int size = userQueryRequest.getPageSize();
        Page<User> userPage = this.page(new Page<>(current, size),
                getQueryWrapper(userQueryRequest));
        List<UserVO> userVOList = getUserVOList(userPage.getRecords());
        Page<UserVO> userVOPage = new Page<>(current,size,userPage.getTotal());
        userVOPage.setRecords(userVOList);
        return userVOPage;
    }

    @Override
    public Boolean isAdmin(User user) {
        return user != null && user.getRole().equals(UserConstant.ADMIN_ROLE);
    }
}




